<template>
  <el-dialog
      v-bind="dialogVisible"
      :title="dialogTitle"
      width="30%"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="视频名称" prop="username">
        <el-input v-model="form.name"/>
      </el-form-item>
      <el-form-item label="视频简介" prop="info">
        <el-input v-model="form.info"/>
      </el-form-item>
      <el-form-item label="视频封面" prop="cover">
        <el-upload
            :headers="headers"
            class="cover-uploader"
            :action="getServerUrl()+'bsns/video/uploadImage'"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeCoverUpload"
        >
          <img v-if="form.cover" :src="form.cover" class="cover"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item  label="视频内容" prop="video">
        <el-upload
            class="avatar-uploader"
            :action="getServerUrl()+'bsns/video/uploadVideo'"
            :on-progress="uploadVideoProcess"
            :on-success="handleVideoSuccess"
            :before-upload="beforeUploadVideo"
            :show-file-list="false"
            :headers="headers"
        >
          <video
              v-if="form.video"
              :src="form.video"
              class="avatar video-avatar"
              controls="controls">
            您的浏览器不支持视频播放
          </video>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="4"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import {defineEmits, defineProps, ref, watch} from "vue"
import requestUtil, {getServerUrl} from "@/util/request";
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import store from '@/store'

const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  }
})
const form = ref({
  id: -1,
  name: "",
  info:"",
  cover: "",
  video: "",
  remark: ""
})
const rules = ref({
  name: [
    {required: true, message: '请输入视频名称'}
  ],
})
const formRef = ref(null)
const initFormData = async (id) => {
  const res = await requestUtil.get("bsns/video/" + id);
  form.value = res.data.bsnsVideo;
}

watch(
    () => props.dialogVisible,
    () => {
      let id = props.id;
      console.log("id=" + id)
      if (id !== -1) {
        initFormData(id);
      } else {
        form.value = {
          id: -1,
          name: "",
          info:"",
          cover: "",
          video: "",
          remark: ""
        }
      }
    }
)
const emits = defineEmits(['update:modelValue', 'initVideoList'])
const handleClose = () => {
  emits('update:modelValue', false)
}
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let result = await requestUtil.post("bsns/video/save", form.value);
      let data = result.data;
      if (data.code === 200) {
        ElMessage.success("执行成功！")
        formRef.value.resetFields();
        emits("initVideoList")
        handleClose();
      } else {
        ElMessage.error(data.msg);
      }
    } else {
      console.log("fail")
    }
  })
}

const headers = ref({
  token: store.getters.GET_TOKEN
})


const handleCoverSuccess = (data) => {
  form.value.cover = data.url;
  ElMessage.success("上传成功")
}

// const beforeCoverUpload = (file) => {
//   const isJPG = file.type === 'image/jpeg'
//   const isLt2M = file.size / 1024 / 1024 < 2
//
//   if (!isJPG) {
//     ElMessage.error('图片必须是jpg格式')
//   }
//   if (!isLt2M) {
//     ElMessage.error('图片大小不能超过2M!')
//   }
//   return isJPG && isLt2M
// }

const beforeCoverUpload = (file) => {
  const fileSize = file.size / 1024 / 1024 < 2

  if ([
    "image/jpeg",
    "image/png",
    "image/gif",
  ].indexOf(file.type) === -1     //控制格式
  ) {
    ElMessage.error("请上传正确的图片格式");
    return false;
  }
  if (!fileSize) {
    ElMessage.error('图片大小不能超过2M!')
    return false;
  }
  return true
}


const videoFlag = ref(false)
const isShowUploadVideo = ref(false)
const videoUploadPercent = ref(0)


const beforeUploadVideo = (file) => {
  const fileSize = file.size / 1024 / 1024 < 50;   //控制大小  修改50的值即可
  if (
      [
        "video/webm",
        "video/mp4",
      ].indexOf(file.type) === -1     //控制格式
  ) {
    ElMessage.error("请上传正确的视频格式，目前只支持webm和mp4格式");
    return false;
  }
  if (!fileSize) {
    ElMessage.error("视频大小不能超过50MB");
    return false;
  }
  isShowUploadVideo.value = false;
}

const uploadVideoProcess = (event, file) => {
  videoFlag.value = true;
  videoUploadPercent.value = file.percentage.toFixed(0) * 1;
}

//上传成功回调
const handleVideoSuccess = (data) => {
  form.value.video = data.url;
  ElMessage.success("上传成功")
}


</script>


<style lang="scss" scoped>
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.cover-uploader .el-upload:hover {
  border-color: #409eff;
}

.el-icon.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 324px;
  height: 216px;
  text-align: center;
}

.cover {
  width: 270px;
  height: 180px;
  display: block;
}

.avatar-uploader-icon {
  border: 1px dashed #d9d9d9 !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px !important;
  position: relative !important;
  overflow: hidden !important;
}

.avatar-uploader .el-upload:hover {
  border: 1px dashed #d9d9d9 !important;
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 300px;
  height: 178px;
  display: block;
}
</style>
